package com.blx.interceptor;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.blx.entity.User;
import com.blx.service.QUserService;
import com.blx.utils.CookieUtil;
import com.blx.utils.annotation.NeedLogin;

public class UserLoginInterceptor extends HandlerInterceptorAdapter{

	protected static final Logger logger = LoggerFactory.getLogger(UserLoginInterceptor.class);
	@Autowired
	private QUserService querService;
	
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws IOException{
		logger.info("@@@ into userLoginInterceptor...");
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("SESSION_USER");
//		if(user == null){
//			logger.info("into autoLogin..");
//			user = autoLogin(request);
//		}
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		if(method.isAnnotationPresent(NeedLogin.class) && null == user){
			if(isAjaxRequest(request)){
				logger.info("ajax request user not login");
				response.setHeader("sessionstatus", "timeout");
				return false;
			}else{
				logger.info("request user not login");
				response.sendRedirect((new StringBuilder()).append(request.getContextPath()).append("/index").toString());
				return false;
			}
		}else{
			return true;
		}
	}
	private boolean isAjaxRequest(HttpServletRequest request){
		String header = request.getHeader("X-requested-With");
		return "XMLHttpRequest".equals(header);
	}
	private User autoLogin(HttpServletRequest request){
		HttpSession session = request.getSession();
		User nowUser = null;
		try {
			String passport = CookieUtil.getCookieByName(request, "loggin_passport");
			String password = CookieUtil.getCookieByName(request, "login_password");
			if(null != passport && null != password){
				Map<String,Object> map = new HashMap<String,Object>();
				nowUser = querService.getQUserEntity(map);
				if(null != nowUser){
					//登陆成功
					session.setAttribute("SESSION_USER", nowUser);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return nowUser;
	}
}
